//家谱
#include <iostream>
#include <map>
using namespace std;
const int MAXN=50000;
map<string,int> ids;
map<string,int>::iterator it;
string names [MAXN+1] ;
struct  UFS
{
    int father[MAXN+1];
    void init(){
        for(int i=1;i<=MAXN;i++) father[i]=i;
    }
    int find_set(int x){
        if (father[x]!=x) father[x]=find_set(father[x]);
        return father[x];
    }
    void union_set(int x,int y){
        int hx=find_set(x);
        int hy=find_set(y);
        father[hy]=hx;
    }
};
UFS ufs;
string curname;
int curid;
int curfather,curson,num;
int main(){
    ufs.init();
    char c;
    cin>>c;
    num=0;
    while(c!='$'){
        cin>>curname;
        it=ids.find(curname);
        if (it==ids.end()){
            num++;
            ids[curname]=num;
            //ids.insert(pair<string,int>(curname,num));
            names[num]=curname;
        }
        curid=ids[curname];
        switch (c)
        {
            case '#':
                curfather=curid;
                break;
            case '+':
                curson=curid;
                ufs.union_set(curfather,curson);
                break;
            case '?':
                int pid=ufs.find_set(curid);
                cout<<curname<<' '<<names[pid]<<endl;
                break;
        }
        cin>>c;
    }
}
